<template>
  <div>
    <el-card class="login-form-layout">
      <el-form autoComplete="on"
               :model="loginForm"
               :rules="loginRules"
               ref="loginForm"
               label-position="left">
        <div style="text-align: center">
          <svg-icon icon-class="login-mall" style="width: 56px;height: 56px;color: #409EFF"></svg-icon>
        </div>
        <h2 class="login-title color-main">后台管理系统</h2>
        <el-form-item prop="username">
          <el-input name="username"
                    type="text"
                    v-model="loginForm.username"
                    autoComplete="on"
                    placeholder="请输入用户名">
          <span slot="prefix">
            <svg-icon icon-class="user" class="color-main"></svg-icon>
          </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password"
                    :type="pwdType"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.password"
                    autoComplete="on"
                    placeholder="请输入密码">
          <span slot="prefix">
            <svg-icon icon-class="password" class="color-main"></svg-icon>
          </span>
            <span slot="suffix" @click="showPwd">
            <svg-icon icon-class="eye" class="color-main"></svg-icon>
          </span>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 60px;text-align: center">
          <el-button style="width: 45%" type="primary" :loading="loading" @click.native.prevent="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- <img :src="login_center_bg" class="login-center-layout"> -->
    <!-- <div @click="handFsLogin">点击获取二维码</div> -->
    <div>飞书扫码登录</div>
    <div id="login_container"></div>
  </div>
</template>
<!-- <script src="https://sf3-cn.feishucdn.com/obj/feishu-static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.2.js"></script> -->
<script>
  import {isvalidUsername} from '@/utils/validate';
  import {setSupport,getSupport,setCookie,getCookie} from '@/utils/support';
  import login_center_bg from '@/assets/images/login_center_bg.png'

  export default {
    name: 'login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.length < 3) {
          callback(new Error('密码不能小于3位'))
        } else {
          callback()
        }
      };
      return {
        loginForm: {
          username: '',
          password: '',
          passwordEncodeYn: false,
          feiShuCode: '',
          loginModeValue: 1  // 1是密码登录 2飞书登录
        },
        loginRules: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePass}]
        },
        loading: false,
        pwdType: 'password',
        login_center_bg,
        dialogVisible:false,
        supportDialogVisible:false,
        QRLoginObj: '', // 是否生成了二维码
		    // client_id: 'cli_a55ed86de8fc900c', // 国斌应用的id
        client_id: 'cli_a56d60acd032100b', // 应用的id
				redirect_uri: 'http://localhost:8090', // 应用配置重定向的地址

		    fs_url: '',
      }
    },
    created() {
      this.loginForm.username = getCookie("username");
      this.loginForm.password = getCookie("password");
      if(this.loginForm.username === undefined||this.loginForm.username==null||this.loginForm.username===''){
        this.loginForm.username = 'admin';
      }
      if(this.loginForm.password === undefined||this.loginForm.password==null){
        this.loginForm.password = 'macro123';
      };
      window.onload = () => {
        // console.log('加载完成', window.location.search, window.location.search.split('='));
        // console.log('打印路径', window.location.href, window.location.pathname);
        const code = window.location.search.split('=');
        if (code.length > 1) {
          this.loginForm.loginModeValue = 2;
          this.loginForm.feiShuCode = code[1];
          this.loginForm.username = '';
          this.loginForm.password = '';
          // console.log('555555', this.loginForm);
          // console.log('打印路径222', window.location.href, window.location.pathname);
          const newHref = window.location.href.split('?');
          this.$store.dispatch('Login', this.loginForm).then(() => {
            this.loading = false;
            setCookie("username",this.loginForm.username,15);
            setCookie("password",this.loginForm.password,15);
            // this.$router.push({path: '/'})
            location.replace(newHref[0]);
          }).catch(() => {
            this.loading = false
          })
        }
      }
      // this.handFsLogin();
    },
    mounted() {
      // console.log('打印路径222', window.location.href, window.location.pathname);
      const href = window.location.href;
      if (href.includes('http://localhost')) {
        this.redirect_uri = 'http://localhost:8090';
      }
      this.handFsLogin();
    },
    methods: {
      handFsLogin() {
        if (this.QRLoginObj !== '') {
          return false;
        } else {
          this.fs_url = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${this.client_id}&redirect_uri=${this.redirect_uri}&response_type=code`;
          this.QRLoginObj = QRLogin({
            id: 'login_container',
            goto: this.fs_url,
            width: '300',
            height: '300',
          })
        };
        if (typeof window.addEventListener != 'undefined') {
           window.addEventListener('message', this.handleMessage, false);
        } else if (typeof window.attachEvent != 'undefined') {
           window.attachEvent('onmessage', this.handleMessage);
        }
      },
      handleMessage(event) {
        // console.log(3333, event);
        // 使用 matchOrigin 和 matchData 方法来判断 message 和来自的页面 url 是否合法
        if (this.QRLoginObj.matchOrigin(event.origin)) {
          var loginTmpCode = event.data;
          console.log('参数所指定的地址1111', loginTmpCode);
          // 链接处理完成后，会重定向到该链接的 redirect_uri 参数所指定的地址，并带上一个授权码（code）
          // 在授权页面地址上拼接上参数 tmp_code，并跳转
          window.location.href = `${this.fs_url}&tmp_code=${loginTmpCode}`;
          //注意：如果跳转的URL和当前页面是同一地址，后续可以通过监听window.onload事件判断页面是否加载完成，再执行其他操作
          // this.loginForm.feiShuCode = loginTmpCode;
          // console.log('555555', this.loginForm);
          // this.$store.dispatch('Login', this.loginForm).then(() => {
          //   this.loading = false;
          //   setCookie("username",this.loginForm.username,15);
          //   setCookie("password",this.loginForm.password,15);
          //   this.$router.push({path: '/'})
          // }).catch(() => {
          //   this.loading = false
          // })
        }
      },
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ''
        } else {
          this.pwdType = 'password'
        }
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store.dispatch('Login', this.loginForm).then(() => {
              this.loading = false;
              setCookie("username",this.loginForm.username,15);
              setCookie("password",this.loginForm.password,15);
              this.$router.push({path: '/'})
            }).catch(() => {
              this.loading = false
            })
          } else {
            console.log('参数验证不合法！');
            return false
          }
        })
      },
      handleTry(){
        this.dialogVisible =true
      },
      dialogConfirm(){
        this.dialogVisible =false;
        setSupport(true);
      },
      dialogCancel(){
        this.dialogVisible = false;
        setSupport(false);
      }
    }
  }
</script>

<style scoped>
  .login-form-layout {
    position: absolute;
    left: 0;
    right: 0;
    width: 360px;
    margin: 140px auto;
    border-top: 10px solid #409EFF;
  }

  .login-title {
    text-align: center;
  }

  .login-center-layout {
    background: #409EFF;
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    margin-top: 200px;
  }
</style>
